package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.base.service.req.GetAuthCodeParam;
import com.iot.base.service.req.RegisterParam;
import com.iot.base.service.resp.GetVerifyCodeResponse;
import com.iot.base.service.resp.RegisterResponse;
import com.iot.common.utils.StringUtils;
import com.iot.sweeper.AppContext;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.bean.CountryCodeBean;
import com.yx.cloud.country.CountryActivity;
import com.yx.cloud.databinding.RegisterActivityBinding;
import com.yx.cloud.utils.AtyContainer;
import com.yx.cloud.utils.CountryCodeUtils;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LanguageUtils;
import com.yx.cloud.utils.RegularCheckUtils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.iot.common.utils.Event;

import java.util.ArrayList;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * 创建时间 : 2018/12/25.
 * 创建人 :
 * 功能描述 :注册界面
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "RegisterTask";
    private String mCountryCode;
    private String type;
    private String account, password, verificationCode;
    private RegisterActivityBinding binding;
    private TimeCount time;
    @Override
    public void onCreate() {
        binding = RegisterActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        //自动获取当前国家代码
        // String contryCode = CountryCodeUtils.getCountryZipCode(this);
        String systemLanguage = LanguageUtils.getSystemLanguage(this);
        String substring = systemLanguage.substring(3, 5);
        ArrayList<CountryCodeBean> codeList = CountryCodeUtils.getCountryCodeList(this);
        for (int i = 0; i < codeList.size(); i++) {
            if (substring.equals("" + codeList.get(i).getLocale())) {
                String countryName = codeList.get(i).getName();
                // LogUtils.i( "-------------------------tvCountryCode :" + codeList.get(i).getName());
                binding.tvRegisterRegion.setText(countryName);
                mCountryCode = codeList.get(i).getCode() + "";
                break;
            }
        }


        setHintByCountryCode();
        //跳槽免责声明弹窗
//        policyPrivacyDialog();
//        Intent intent = new Intent(this, DisclaimerDialog.class);
//        startActivityForResult(intent, 2);

        binding.btnGoRegister.setEnabled(false);
        binding.etRegisterPhonenum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (binding.cbxRegisterAgreeProtocol.isChecked()) {
                    if (!"".equals(editable.toString().trim()) &&
                            binding.etRegisterVerificationCode.length() >= 4 &&
                            binding.etRegisterSetNewPassWord.length() >= 6 &&
                            binding.etRegisterNewPassWord.length() >= 6
                    ) {
                        binding.btnGoRegister.setEnabled(true);
                    } else {
                        binding.btnGoRegister.setEnabled(false);
                    }
                }
            }
        });
        binding.etRegisterVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (binding.cbxRegisterAgreeProtocol.isChecked()) {
                    if (!"".equals(editable.toString().trim()) &&
                            binding.etRegisterVerificationCode.length() >= 4 &&
                            binding.etRegisterSetNewPassWord.length() >= 6 &&
                            binding.etRegisterNewPassWord.length() >= 6) {
                        binding.btnGoRegister.setEnabled(true);
                    } else {
                        binding.btnGoRegister.setEnabled(false);
                    }
                }
            }
        });
        /**
         * 对帐号密码输入框进行监听
         */
        binding.etRegisterSetNewPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString().trim()) &&
                        binding.etRegisterVerificationCode.length() >= 4 &&
                        binding.etRegisterSetNewPassWord.length() >= 6 &&
                        binding.etRegisterNewPassWord.length() >= 6) {
                    binding.btnGoRegister.setEnabled(true);
                } else {
                    binding.btnGoRegister.setEnabled(false);
                }
            }
        });
        binding.etRegisterNewPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!"".equals(editable.toString().trim()) &&
                        binding.etRegisterVerificationCode.length() >= 4 &&
                        binding.etRegisterSetNewPassWord.length() >= 6 &&
                        binding.etRegisterNewPassWord.length() >= 6) {
                    binding.btnGoRegister.setEnabled(true);
                } else {
                    binding.btnGoRegister.setEnabled(false);
                }
            }
        });


        binding.cbxRegisterAgreeProtocol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (binding.etRegisterPhonenum.length() > 0) {
                        binding.btnGoRegister.setEnabled(true);
                    } else {
                        binding.btnGoRegister.setEnabled(false);
                    }
                } else {
                    binding.btnGoRegister.setEnabled(false);
                }
            }
        });

        binding.ivNewRegisterReturn.setOnClickListener(this);
        binding.btnGoRegister.setOnClickListener(this);
        binding.rlRegisterSelectRegion.setOnClickListener(this);
        binding.ivClear.setOnClickListener(this);
        binding.tvFindResend.setOnClickListener(this);
        binding.tbRegisterAffirmPassword.setOnClickListener(this);
        binding.tbRegisterSetPassword.setOnClickListener(this);

        String agree=binding.cbxRegisterAgreeProtocol.getText().toString();
        SpannableString builder=new SpannableString(agree);
        String serviceProtocol=getString(R.string.L_Privacy_Llink_Serve);
        int indexServiceProtocol=agree.indexOf(serviceProtocol);
        int endServiceProtocol=indexServiceProtocol+serviceProtocol.length();
        String privacyPolicy=getString(R.string.L_Privacy_Llink_Privacy);
        int indexPrivacyPolicy=agree.indexOf(privacyPolicy);
        int endPrivacyPolicy=indexPrivacyPolicy+privacyPolicy.length();

        ClickableSpan serviceProtocolClickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent_utils.enterIntentContext(RegisterActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Server");
            }
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        ClickableSpan privacyPolicyClickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent_utils.enterIntentContext(RegisterActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Privacy");
            }
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        builder.setSpan(serviceProtocolClickableSpan ,indexServiceProtocol,endServiceProtocol, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(privacyPolicyClickableSpan ,indexPrivacyPolicy,endPrivacyPolicy, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);


        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(getColor(R.color.button_color2));
        builder.setSpan(foregroundColorSpan, indexServiceProtocol, endServiceProtocol, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(getColor(R.color.button_color2));
        builder.setSpan(foregroundColorSpan1, indexPrivacyPolicy, endPrivacyPolicy, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        binding.cbxRegisterAgreeProtocol.setMovementMethod(LinkMovementMethod.getInstance());
        binding.cbxRegisterAgreeProtocol.setText(builder);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_newRegister_return) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.rl_register_selectRegion) {
            Log.d(TAG, "cccccccccccccccc");
            Intent intenta = new Intent(this, CountryActivity.class);
            startActivityForResult(intenta, 1);
        } else if (id == R.id.tv_find_resend) {
            //获取验证码
            if (time == null) {
                //获取验证码计时
                time = new TimeCount(60000, 1000);
                time.start();
            }
            account = binding.etRegisterPhonenum.getText().toString().trim();
            GetAuthCodeParam param = new GetAuthCodeParam();
            param.setCountryCode(mCountryCode);
            param.setAccount(account);
            param.setType(GetAuthCodeParam.TYPE_REGISTER);
            AppContext.getAccountService().getAuthCode(param);
        } else if (id == R.id.btn_GoRegister) {
            //注册
            account = binding.etRegisterPhonenum.getText().toString().trim();
            password = binding.etRegisterNewPassWord.getText().toString().trim();
            String setNewPassWord = binding.etRegisterSetNewPassWord.getText().toString().trim();
            verificationCode = binding.etRegisterVerificationCode.getText().toString().trim();

            if (account.isEmpty()) {
                Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_LONG).show();
                return;
            }
            if (verificationCode.isEmpty()) {
                Toast.makeText(this, getString(R.string.U_T_Code_No), Toast.LENGTH_LONG).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, getString(R.string.U_T_Pw_Null), Toast.LENGTH_LONG).show();
                return;
            }
            if (!password.equals(setNewPassWord)) {
                Toast.makeText(this, getString(R.string.U_T_Pw_NoAgain), Toast.LENGTH_LONG).show();
                return;
            }
            if (RegularCheckUtils.isMobile(account)) {
                type = "phone";
            } else {
                if (RegularCheckUtils.isEmail(account)) {
                    type = "email";
                } else {
                    Toast.makeText(this, getString(R.string.U_T_Un_NoFormat), Toast.LENGTH_LONG).show();
                    return;
                }
            }
            if (!binding.cbxRegisterAgreeProtocol.isChecked()) {
                Toast.makeText(this, getString(R.string.L_T_Agree_Privacy), Toast.LENGTH_LONG).show();
                return;
            }

            RegisterParam registerParam = new RegisterParam();
            registerParam.setAccount(account);
            registerParam.setCode(verificationCode);
            registerParam.setPassword(password);
            registerParam.setCountryCode(mCountryCode);
            AppContext.getAccountService().register(registerParam); //验证码检验

        }else if (id == R.id.iv_clear) {
            binding.etRegisterPhonenum.setText("");
        }else if (id == R.id.tb_register_setPassword) {
            if (binding.tbRegisterSetPassword.isChecked()) {
                binding.etRegisterSetNewPassWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            } else {
                binding.etRegisterSetNewPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            }
            binding.etRegisterSetNewPassWord.setSelection(binding.etRegisterSetNewPassWord.getText().toString().trim().length());
        }else if (id == R.id.tb_register_AffirmPassword) {
            if (binding.tbRegisterAffirmPassword.isChecked()) {
                binding.etRegisterNewPassWord.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            } else {
                binding.etRegisterNewPassWord.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            }
            binding.etRegisterNewPassWord.setSelection(binding.etRegisterNewPassWord.getText().toString().trim().length());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_GET_AUTH_CODE:
                //获取验证码
                Log.d(TAG, "cccccccfffffffffffffffffffff ，，，，，，，，，，，，，，，，，，，，，，，，" + mCountryCode);
                if (event.isResult()) {
                    //发送验证码成功 不处理
                } else {
                    GetVerifyCodeResponse response = (GetVerifyCodeResponse) event.getContent();
                    if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_REGISTER_CODE_USER_EXIST) {
                        //注册验证码的用户已存在
                        ToastUtil.showShort(this, getString(R.string.L_T_Register_Un_Existed));
                    }else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_CHANGE_PASSWORD_USER_NOT_EXIST) {
                        //修改密码验证码的用户不存在
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_No));
                    }  else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_REQUEST_COUNT_LIMIT) {
                        //验证码请求次数限制
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_TimesLimit));
                    } else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_REQUEST_FREQUENCY_LIMIT) {
                        //验证码请求太过频繁 一分钟三次
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_Frequently));
                    } else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_INVALID_ACCOUNT_FORMAT) {
                        //账号格式错误
                        ToastUtil.showShort(this, getString(R.string.U_T_Un_NoFormat));
                    }else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_NETWORK) {
                        ToastUtil.showShort(this,getString(R.string.U_T_Network_Err));
                    }else if (response.getErrorCode()== GetVerifyCodeResponse.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                    }
                }
                break;
            case Event.MESSAGE_TYPE_REGISTER:
                //注册
                if (event.isResult()) {
                    Toast.makeText(this, getString(R.string.L_T_Register_Ok), Toast.LENGTH_LONG).show();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //注册成功后立即登录
                    AtyContainer.getInstance().finishAllActivity(); //在登录界面点击返回键退出程序
                    Intent_utils.enterIntent(this, LoginActivity.class);
                } else {
                    Toast.makeText(this, event.getContent().toString(), Toast.LENGTH_LONG).show();

                    RegisterResponse response = (RegisterResponse) event.getContent();
                    if (response.getErrorCode()== RegisterResponse.ERROR_VERIFY_CODE) {
                        //验证码错误
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_No));
                    } else if (response.getErrorCode()== RegisterResponse.ERROR_VERIFY_CODE_EXPIRED) {
                        //验证码过期
                        ToastUtil.showShort(this, getString(R.string.U_T_Code_Expired));
                    } else if (response.getErrorCode()== RegisterResponse.ERROR_USER_EXIST) {
                        ToastUtil.showShort(this, getString(R.string.L_T_Register_Un_Existed));
                    }else if (response.getErrorCode()== RegisterResponse.ERROR_NETWORK) {
                        ToastUtil.showShort(this,getString(R.string.U_T_Network_Err));
                    }else if (response.getErrorCode()== RegisterResponse.ERROR_SERVER) {
                        ToastUtil.showShort(this, getString(R.string.U_T_Server_Err));
                    } else {
                        ToastUtil.showShort(this, getString(R.string.U_UnknownErr));
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 2) {
                String countryCode = data.getStringExtra("countryCode");
                Log.d(TAG, "cccccccfffffffffffffffffffff " + countryCode);
                String countryName = data.getStringExtra("countryName");
//                String en = data.getStringExtra("en");
                binding.tvRegisterRegion.setText(countryName);
                binding.tvCountrycodeCode.setText(countryCode);
                mCountryCode = countryCode;
                setHintByCountryCode();
            }
        }

    }

    private void setHintByCountryCode() {
        if (!mCountryCode.equals("86")) {
            binding.etRegisterPhonenum.setHint(getString(R.string.MY_Email));
        } else {
            binding.etRegisterPhonenum.setHint(getString(R.string.U_Un_Hint));
        }
    }
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            binding.tvFindResend.setClickable(false);
            binding.tvFindResend.setText(getResources().getString(R.string.U_AgainGet_Btn) + "(" + millisUntilFinished / 1000 + ")");
        }

        @Override
        public void onFinish() {
            binding.tvFindResend.setText(getResources().getString(R.string.U_GetCode_Btn));
            binding.tvFindResend.setClickable(true);
            time = null;
        }
    }



    /**
     * 政策隐私弹框
     */
    private void policyPrivacyDialog() {
        Dialog dialog = new Dialog(RegisterActivity.this);
        dialog.setContentView(R.layout.disclaimer_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);

        TextView mTvConsent = dialog.findViewById(R.id.btn_agree);
        TextView mTvReject = dialog.findViewById(R.id.btn_reject);
        TextView mTvDisclaimerServer = dialog.findViewById(R.id.tv_disclaimerServer);
        TextView mTvDisclaimerPrivacy = dialog.findViewById(R.id.tv_disclaimerPrivacy);

        mTvDisclaimerServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.enterIntentContext(RegisterActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Server");
            }
        });
        mTvDisclaimerPrivacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                Intent_utils.enterIntentContext(RegisterActivity.this, ServerAndPrivacyActivity.class, "Server_Privacy", "Privacy");
            }
        });


        mTvConsent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                SharedPrefsUtil.putValue(RegisterActivity.this, "ServerAndPrivacySign", "ServerAndPrivacySign", true);
                dialog.dismiss();
            }
        });
        mTvReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                SharedPrefsUtil.putValue(RegisterActivity.this, "ServerAndPrivacySign", "ServerAndPrivacySign", false);
                dialog.dismiss();
                Intent_utils.backIntent(RegisterActivity.this);
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


}
